package com.biostime.springdraw.modules.sys.web;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.shiro.authz.annotation.Logical;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import com.biostime.springdraw.common.config.Global;
import com.biostime.springdraw.common.persistence.Page;
import com.biostime.springdraw.common.utils.StringUtils;
import com.biostime.springdraw.common.web.BaseController;
import com.biostime.springdraw.modules.sys.entity.Dict;
import com.biostime.springdraw.modules.sys.service.DictService;

/**
 * 字典表Controller
 * @author phil
 * @version 2015-11-06
 */
@Controller
@RequestMapping(value = "${adminPath}/sys/dict")
public class DictController extends BaseController {

	@Autowired
	private DictService dictService;
	
	@ModelAttribute
	public Dict get(@RequestParam(required=false) String id) {
		Dict entity = null;
		if (StringUtils.isNotBlank(id)){
			entity = dictService.get(id);
		}
		if (entity == null){
			entity = new Dict();
		}
		return entity;
	}
	
	@RequiresPermissions("sys:dict:view")
	@RequestMapping(value = {"list", ""})
	public String list(Dict dict, HttpServletRequest request, HttpServletResponse response, Model model) {
		Page<Dict> page = dictService.findPage(new Page<Dict>(request, response), dict); 
		model.addAttribute("page", page);
		return "modules/sys/dictList";
	}

	@RequiresPermissions("sys:dict:view")
	@RequestMapping(value = "form")
	public String form(Dict dict, Model model) {
		model.addAttribute("dict", dict);
		return "modules/sys/dictForm";
	}

	@RequiresPermissions(value={"sys:dict:edit","sys:dict:add"}, logical=Logical.OR)
	@RequestMapping(value = "save")
	public String save(Dict dict, Model model, RedirectAttributes redirectAttributes) {
		if (!beanValidator(model, dict)){
			return form(dict, model);
		}
		
		dictService.save(dict);
		addMessage(redirectAttributes, "保存成功");
		return "redirect:"+Global.getAdminPath()+"/sys/dict/?repage";
	}
	
	@RequiresPermissions("sys:dict:edit")
	@RequestMapping(value = "delete")
	public String delete(@RequestParam(value="ids",required=false) String idsRequest, Dict dict, RedirectAttributes redirectAttributes) {
		
		//批量删除
		if(!StringUtils.isEmpty(idsRequest)){
			String[] ids = idsRequest.split(",");
			for(String id : ids){
				dictService.delete(new Dict(id));
			}
		}else{
			dictService.delete(dict);
		}
		
		addMessage(redirectAttributes, "删除成功");
		return "redirect:"+Global.getAdminPath()+"/sys/dict/?repage";
	}

}